import cv2

import numpy as np

def cv2_imshow(img):
    cv2.imshow("result",img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# Reading the original image
image_spot = cv2.imread("D:\\data\\CUGW\\side\\IMG_5469.JPG")

image_spot_reshaped = image_spot.reshape((image_spot.shape[0] * image_spot.shape[1], 3))    #二维转一维

# convert to np.float32
Z = np.float32(image_spot)
# define criteria, number of clusters(K) and apply kmeans() #定义停止条件
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)    #迭代次数，中心移动值
K = 8   #聚类类别数
ret, label, center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((image_spot.shape))
cv2.imwrite("imgs_out/imgKmeans.jpg", res2)
cv2_imshow(res2)
# ————————————————
# 版权声明：本文为CSDN博主「woshicver」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
# 原文链接：https://blog.csdn.net/woshicver/article/details/124854633